/*
 * TCriticalSection.cpp
 *
 *  Created on: 2012-10-30
 *      Author: minhua
 */

#include "TCriticalSection.h"

#include <QThread>
#include <QUuid>
#include <QVariant>

TCriticalSection::TCriticalSection()
{
    //_key = QUuid::createUuid().toString().toStdString();
}

int TCriticalSection::getEnterCount()
{
    Qt::HANDLE handle = QThread::currentThreadId();
    QHash<Qt::HANDLE, int>::iterator it = _threadIdHash.find(handle);
    if (it == _threadIdHash.end())
        return 0;

    return it.value();
}

void TCriticalSection::setEnterCount(int count)
{
    Qt::HANDLE handle = QThread::currentThreadId();
    _threadIdHash[handle] = count;
}

void TCriticalSection::lock()
{
    QThread    *curThread  = QThread::currentThread();
    if (curThread == NULL)
        return;

    int curCount = getEnterCount();
    if (curCount == 0)
    {
        _mutex.lock();
    }
    curCount++;
    setEnterCount(curCount);
}

void TCriticalSection::unlock()
{
    QThread     *curThread  = QThread::currentThread();
    if (curThread == NULL)
        return;

    int curCount = getEnterCount();

    curCount--;
    if (curCount < 0)
        return;

    if (curCount == 0)
        _mutex.unlock();

    setEnterCount(curCount);
}

TCriticalSectionLocker::TCriticalSectionLocker(TCriticalSection *criticalSection)
{
    _criticalSection = criticalSection;
    lock();

}

TCriticalSectionLocker::~TCriticalSectionLocker()
{
    unlock();
}

void TCriticalSectionLocker::lock()
{
    _criticalSection->lock();
}

void TCriticalSectionLocker::unlock()
{
    _criticalSection->unlock();
}
